package com.malty.apimanage.service.impl.inner;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.malty.apimanage.service.UserApiInfoService;
import com.malty.common.ErrorCode;
import com.malty.common.api.InnerUserApiInfoService;
import com.malty.common.domain.entity.UserApiInfo;
import com.malty.common.exception.BusinessException;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Administrator
 * @description 针对表【user_api_info】的数据库操作Service实现
 * @createDate 2025-09-29 15:52:00
 */
@DubboService
public class InnerUserApiInfoServiceImpl implements InnerUserApiInfoService {
    @Autowired
    private UserApiInfoService userApiInfoService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean increaseUserApiInvokeCount(Long userId, Long apiId) {
        UserApiInfo userApiInfo = userApiInfoService.getUserApiInfo(userId, apiId);

        if (userApiInfo.getId() == null) {
            userApiInfo = new UserApiInfo(userId, apiId);
            userApiInfo.setUsedCalls(0L);
            userApiInfo.setAvailableCalls(10L);
            userApiInfoService.save(userApiInfo);
        }

        if (userApiInfo.getAvailableCalls() <= 0) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "调用次数已用完");
        }

        UpdateWrapper<UserApiInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("api_id", apiId)
                .eq("user_id", userId)
                .gt("available_calls", 0);

        updateWrapper.setSql("available_calls = available_calls - 1, used_calls = used_calls + 1");

        return userApiInfoService.update(updateWrapper);
    }
}




